package com.ztao.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.model.common.admin.dto.NewsAuthDto;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.wemedia.dtos.WmNewsDownOrUpDto;
import com.heima.model.common.wemedia.dtos.WmNewsDto;
import com.heima.model.common.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.common.wemedia.pojos.WmMaterial;
import com.heima.model.common.wemedia.pojos.WmNews;
import com.heima.model.common.wemedia.pojos.WmNewsMaterial;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.ztao.common.constants.WemediaConstants;
import com.ztao.mapper.WmMaterialMapper;
import com.ztao.mapper.WmNewsMapper;
import com.ztao.mapper.WmNewsMaterialMapper;
import com.ztao.service.WmNewsAutoScanService;
import com.ztao.service.WmNewsService;
import com.ztao.service.WmNewsTaskService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

@Service
public class WmNewsServiceImpl implements WmNewsService {
    @Resource
    private WmNewsMapper wmNewsMapper;

    //媒体审核
    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {
        dto.checkParam();
        IPage<WmNews> page = new Page<>(dto.getPage(), dto.getSize());
        QueryWrapper<WmNews> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(dto.getStatus() != null, WmNews::getStatus, dto.getStatus());
        queryWrapper.lambda().eq(dto.getKeyword() != null, WmNews::getTitle, dto.getKeyword());
        queryWrapper.lambda().eq(dto.getChannelId() != null, WmNews::getChannelId, dto.getChannelId());
        queryWrapper.lambda().eq(WmNews::getUserId, WmThreadLocalUtil.getUser().getId());
        queryWrapper.lambda().orderByDesc(WmNews::getCreatedTime);
        if (dto.getBeginPubDate() != null && dto.getEndPubDate() != null) {
            queryWrapper.lambda().between(WmNews::getPublishTime, dto.getBeginPubDate(), dto.getEndPubDate());
        }
        page = this.wmNewsMapper.selectPage(page, queryWrapper);
        ResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        result.setData(page.getRecords());
        return result;

    }

    @Override
    public ResponseResult delNews(Integer id) {
        int i = this.wmNewsMapper.deleteById(id);
        return ResponseResult.okResult(i);
    }

    @Resource
    private WmNewsMaterialMapper wmNewsMaterialMapper;
    @Resource
    private WmMaterialMapper wmMaterialMapper;
    @Resource
    private WmNewsTaskService wmNewsTaskService;
    @Resource
    private KafkaTemplate<String, String> kafkaTemplate;


@Override
public ResponseResult submitNews(WmNewsDto dto) {
    //1.检查查询
    if (dto==null){
        return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
    }

    //2.把参封装一下
    WmNews wmNews=new WmNews();
    BeanUtils.copyProperties(dto,wmNews);
    //3.补全属性
    wmNews.setUserId(WmThreadLocalUtil.getUser().getId());
    wmNews.setCreatedTime(new Date());
    wmNews.setEnable((short) 1);
    //提交时间
    if (dto.getStatus()==1){
        wmNews.setSubmitedTime(new Date());
    }
    //4.获取文章的封面
    if (dto.getImages()!=null && dto.getImages().size()>0){
        //前端传递的是一个集合 数据库里面需要的时候字符串用，隔开
        String images= StringUtils.join(dto.getImages(),",");
        wmNews.setImages(images);
    }

    //处理tinyint 不能是负数 -1 --> 4
    if (dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)) {
        dto.setType((short) 4);
        wmNews.setType((short) 4);
    }

    //判断是否是新增操作还是修改操作
    if (dto.getId()==null){ //新增
        wmNewsMapper.insert(wmNews); //5.添加数据库

    }else { //修改操作 -需要删除素材与内容/封面的关系

        //删除关联关系
        Integer newsId=dto.getId();
        QueryWrapper<WmNewsMaterial> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().eq(WmNewsMaterial::getNewsId,newsId);
        wmNewsMaterialMapper.delete(queryWrapper);
        //修改
        wmNewsMapper.updateById(wmNews);
    }

    //新增关联
    //处理封面 封面是自己上传的/封面是自动获取的
    if (dto.getType()!=4){ //图片是自己上传的
        List<String> images=dto.getImages();
        //把url转换成id
        List<Integer> mids=new ArrayList<>();
        for (String img:images){
            QueryWrapper<WmMaterial> materQ=new QueryWrapper<>();
            materQ.lambda().eq(WmMaterial::getUrl,img);
            WmMaterial wmMaterial=wmMaterialMapper.selectOne(materQ);
            mids.add(wmMaterial.getId());
        }

        //把关系维护进去
        if (mids.size()>0){
            wmNewsMaterialMapper.saveRelations(mids, wmNews.getId(), (short)1);
        }
    }else { //自动获取封面
        //如何自动获取封面 从内容里面获取

        List<String> images=new ArrayList<>();

        List<Map> maps= JSON.parseArray(dto.getContent(),Map.class);
        for (Map map:maps){
            //传递过来是个照片
            if (map.get("type").equals("image")){
                //把获取到的图片保存到images里面 -list集合
                images.add((String)map.get("value"));
            }
        }

        if (images.size()==0){ //内容里面是没有图片的
            //没有图片的 页面是没有4的局部的 0 1 3   没有图片，布局就是0
            WmNews wmNews1=new WmNews();
            wmNews1.setId(wmNews1.getId());
            wmNews1.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            wmNewsMapper.updateById(wmNews1);
        }else{ //内容里面是有图片的 把图片设置成封面
            //有图片的
            if (images.size()==1 || images.size()==2){
                List<String> topThreeImages = images.subList(0, 1);
                //修改type=1
                WmNews wmNews1=new WmNews();
                wmNews1.setId(wmNews.getId());
                wmNews1.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);

                //1.news表里面的images字段
                String newsImages=StringUtils.join(topThreeImages,",");
                wmNews1.setImages(newsImages);
                wmNewsMapper.updateById(wmNews1);

                List<Integer> mids=new ArrayList<>();
                for (String img:images){
                    //2.处理素材与news的关系
                    QueryWrapper<WmMaterial> materQ=new QueryWrapper<>();
                    materQ.lambda().eq(WmMaterial::getUrl,img);
                    WmMaterial wmMaterial=wmMaterialMapper.selectOne(materQ);
                    mids.add(wmMaterial.getId());
                }
                //把关系维护进去
                if (mids.size()>0){
                    wmNewsMaterialMapper.saveRelations(mids, wmNews.getId(), (short)1);
                }
            }
            if (images.size()>=3){
                List<String> topThreeImages = images.subList(0, 3);
                //修改type=3
                WmNews wmNews1=new WmNews();
                wmNews1.setId(wmNews.getId());
                wmNews1.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);

                //1.news表里面的images字段
                String newsImages=StringUtils.join(topThreeImages,",");
                wmNews1.setImages(newsImages);
                wmNewsMapper.updateById(wmNews1);

                List<Integer> mids=new ArrayList<>();
                for (String img:images){
                    //2.处理素材与news的关系
                    QueryWrapper<WmMaterial> materQ=new QueryWrapper<>();
                    materQ.lambda().eq(WmMaterial::getUrl,img);
                    WmMaterial wmMaterial=wmMaterialMapper.selectOne(materQ);
                    mids.add(wmMaterial.getId());
                }
                //把关系维护进去
                if (mids.size()>0){
                    wmNewsMaterialMapper.saveRelations(mids, wmNews.getId(), (short)1);
                }
            }
        }
    }
    //处理内容与素材直接的关系  从里面把素材获取到url  --id 添加操作

    //如果状态是0 草稿 1状态是1 -->待审核 【自动审核 人工审核】
    if (dto.getStatus()==1){
        //调用了自动审核的方法
//            wmNewsAutoScanService.autoScanWmNews(wmNews.getId());
        //list zset zset-list
        wmNewsTaskService.addNewsToTask(wmNews);
    }
    return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
}

    /**
     * 文章上下架
     *
     * @param dto
     */
    @Override
    public ResponseResult downOrUp(WmNewsDownOrUpDto dto) {
        //1.校验参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        if (dto.getId() == null) {
            return ResponseResult.errorResult(501, "文章id不能缺少");
        }
        //2.查询文章
        WmNews wmNews = wmNewsMapper.selectById(dto.getId());
        if (wmNews == null) {
            return ResponseResult.errorResult(1002, "文章id不存在");
        }

        //3.判断文章的发布状态  -审核通过
        // 如果是8表示审核通过    - 9已经同步到文章微服务了
        if (! wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            return ResponseResult.errorResult(501, "文章没有审核通过不能发布");
        }

        //修改操作
        wmNews.setEnable(dto.getEnable());
        wmNewsMapper.updateById(wmNews);

        //把消息发送到kafka里面
        if(wmNews.getArticleId()!=null){
            Map<String, Object> map = new HashMap<>();
            map.put("articleId",wmNews.getArticleId());
            map.put("enable",dto.getEnable());

            System.out.println("发送消息===================");
            kafkaTemplate.send("articleDownOrUp444",JSON.toJSONString(map));

        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }



}

